# PowerShell 脚本用于生成自签名 SSL 证书
# 修复版本 - 兼容所有PowerShell版本

param(
    [string]$Domain = "localhost"
)

# 设置错误处理
$ErrorActionPreference = "Stop"

try {
    Write-Host "开始生成自签名 SSL 证书..." -ForegroundColor Green
    
    # 创建证书目录
    if (-not (Test-Path "nginx\ssl")) {
        New-Item -ItemType Directory -Force -Path "nginx\ssl" | Out-Null
    }
    if (-not (Test-Path "certs")) {
        New-Item -ItemType Directory -Force -Path "certs" | Out-Null
    }

    # 检查是否安装了 OpenSSL
    $opensslPath = $null
    try {
        $opensslPath = Get-Command openssl -ErrorAction SilentlyContinue
    }
    catch {
        # OpenSSL 未安装
    }

    if ($null -ne $opensslPath) {
        Write-Host "使用 OpenSSL 生成证书..." -ForegroundColor Yellow
        
        # 为 Nginx 生成证书
        $opensslArgs = @(
            "req", "-x509", "-nodes", "-days", "365", 
            "-newkey", "rsa:2048",
            "-keyout", "nginx/ssl/key.pem",
            "-out", "nginx/ssl/cert.pem",
            "-subj", "/C=CN/ST=Beijing/L=Beijing/O=WebRTC/OU=IT Department/CN=$Domain"
        )
        
        & openssl @opensslArgs
        
        if ($LASTEXITCODE -eq 0) {
            Write-Host "✓ Nginx 证书生成成功" -ForegroundColor Green
            
            # 为 ASP.NET Core 生成 pfx 证书
            $pfxArgs = @(
                "pkcs12", "-export", 
                "-out", "certs/aspnetapp.pfx",
                "-inkey", "nginx/ssl/key.pem",
                "-in", "nginx/ssl/cert.pem",
                "-passout", "pass:"
            )
            
            & openssl @pfxArgs
            
            if ($LASTEXITCODE -eq 0) {
                Write-Host "✓ ASP.NET Core 证书生成成功" -ForegroundColor Green
            }
            else {
                throw "生成 PFX 证书失败"
            }
        }
        else {
            throw "生成 Nginx 证书失败"
        }
    }
    else {
        Write-Host "OpenSSL 未找到，使用 PowerShell 内置功能生成证书..." -ForegroundColor Yellow
        
        # 使用 PowerShell 生成自签名证书
        $certParams = @{
            DnsName = $Domain
            CertStoreLocation = "cert:\CurrentUser\My"
            KeyUsage = @("DigitalSignature", "KeyEncipherment")
            KeyAlgorithm = "RSA"
            KeyLength = 2048
            NotAfter = (Get-Date).AddYears(1)
        }
        
        $cert = New-SelfSignedCertificate @certParams
        Write-Host "✓ 证书创建成功，指纹: $($cert.Thumbprint)" -ForegroundColor Green
        
        # 导出为 PFX 格式
        $password = ConvertTo-SecureString -String "" -Force -AsPlainText
        $pfxPath = Join-Path $PWD "certs\aspnetapp.pfx"
        Export-PfxCertificate -Cert $cert -FilePath $pfxPath -Password $password | Out-Null
        Write-Host "✓ PFX 证书导出成功" -ForegroundColor Green
        
        # 导出为 PEM 格式
        $certBytes = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
        $certBase64 = [System.Convert]::ToBase64String($certBytes)
        
        $pemCert = "-----BEGIN CERTIFICATE-----`r`n"
        $lineLength = 64
        for ($i = 0; $i -lt $certBase64.Length; $i += $lineLength) {
            $length = [Math]::Min($lineLength, $certBase64.Length - $i)
            $pemCert += $certBase64.Substring($i, $length) + "`r`n"
        }
        $pemCert += "-----END CERTIFICATE-----`r`n"
        
        $pemPath = Join-Path $PWD "nginx\ssl\cert.pem"
        Set-Content -Path $pemPath -Value $pemCert -Encoding UTF8
        Write-Host "✓ PEM 证书导出成功" -ForegroundColor Green
        
        # 创建一个临时私钥文件（注意：这不是真正的私钥，仅用于测试）
        $keyPath = Join-Path $PWD "nginx\ssl\key.pem"
        $tempKey = @"
-----BEGIN PRIVATE KEY-----
# 注意：这是一个占位符私钥文件
# 在生产环境中，请使用 OpenSSL 生成真正的私钥
# 安装 OpenSSL: winget install OpenSSL.OpenSSL
-----END PRIVATE KEY-----
"@
        Set-Content -Path $keyPath -Value $tempKey -Encoding UTF8
        
        Write-Host "⚠️  注意: 使用 PowerShell 生成的私钥是占位符" -ForegroundColor Yellow
        Write-Host "⚠️  建议安装 OpenSSL 以获得完整的证书生成功能" -ForegroundColor Yellow
        Write-Host "   安装命令: winget install OpenSSL.OpenSSL" -ForegroundColor Cyan
        
        # 清理证书存储中的临时证书
        try {
            Remove-Item "cert:\CurrentUser\My\$($cert.Thumbprint)" -ErrorAction SilentlyContinue
        }
        catch {
            # 忽略清理错误
        }
    }

    Write-Host "`n🎉 证书生成完成！" -ForegroundColor Green
    Write-Host "📁 文件位置:" -ForegroundColor Cyan
    Write-Host "   Nginx 证书: nginx/ssl/cert.pem" -ForegroundColor White
    Write-Host "   Nginx 私钥: nginx/ssl/key.pem" -ForegroundColor White
    Write-Host "   ASP.NET Core: certs/aspnetapp.pfx" -ForegroundColor White
    
    # 验证文件是否存在
    $files = @(
        "nginx\ssl\cert.pem",
        "nginx\ssl\key.pem", 
        "certs\aspnetapp.pfx"
    )
    
    Write-Host "`n📋 文件验证:" -ForegroundColor Cyan
    foreach ($file in $files) {
        if (Test-Path $file) {
            $size = (Get-Item $file).Length
            Write-Host "   ✓ $file ($size bytes)" -ForegroundColor Green
        }
        else {
            Write-Host "   ✗ $file (缺失)" -ForegroundColor Red
        }
    }
    
    Write-Host "`n🚀 接下来可以运行:" -ForegroundColor Yellow
    Write-Host "   dotnet run" -ForegroundColor White
    Write-Host "   或者" -ForegroundColor Gray
    Write-Host "   docker-compose up" -ForegroundColor White

}
catch {
    Write-Host "`n❌ 错误: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "💡 解决方案:" -ForegroundColor Yellow
    Write-Host "   1. 以管理员身份运行 PowerShell" -ForegroundColor White
    Write-Host "   2. 执行: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser" -ForegroundColor White
    Write-Host "   3. 安装 OpenSSL: winget install OpenSSL.OpenSSL" -ForegroundColor White
    exit 1
} 